<template>
  <div class="system-dic-container layout-padding">
    <!-- 搜索卡片 -->
    <el-card shadow="hover" class="mb10">
      <div class="system-user-search">
        <el-row :gutter="20">
          <!-- 时间范围选择 -->
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-date-picker
                v-model="searchParams.dataTime"
                type="datetimerange"
                size="default"
                style="width: 100%"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-col>

          <!-- 井位置选择 -->
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-select
                v-model="searchParams.jid"
                size="default"
                placeholder="请选择井的位置"
                clearable
                style="width: 100%"
            >
              <el-option
                  v-for="item in wellList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-col>

          <!-- 支付状态 -->
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="支付状态:" class="ml10">
              <el-radio-group size="default" v-model="searchParams.payStatus">
                <el-radio-button label="0">未支付</el-radio-button>
                <el-radio-button label="1">已支付</el-radio-button>
                <el-radio-button label="">全部</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <!-- 搜索输入 -->
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-input
                v-model="searchParams.keyword"
                size="default"
                placeholder="请输入用户名称/手机号"
                clearable
            >
              <template #append>
                <el-button :icon="Search" @click="handleSearch" />
              </template>
            </el-input>
          </el-col>

          <!-- 操作按钮 -->
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mt10 text-right">
            <el-button
                size="default"
                type="success"
                :icon="FolderAdd"
                @click="handleAddRecord"
            >
              新增记录
            </el-button>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table
          :data="tableData"
          height="calc(100vh - 400px)"
          :header-cell-style="{ background: '#EEEEEE' }"
          style="width: 100%"
          stripe
      >
        <el-table-column prop="id" label="序号" width="80" align="center" />
        <el-table-column prop="uname" label="用户名称" align="center" />
        <el-table-column prop="uphone" label="手机号" align="center" width="120" />
        <el-table-column prop="jname" label="井名称" align="center" show-overflow-tooltip />

        <el-table-column prop="startTime" label="开始时间" align="center" width="180">
          <template #default="{row}">
            <span v-if="row.startTime">{{ formatDateNew(row.startTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="endTime" label="结束时间" align="center" width="180">
          <template #default="{row}">
            <span v-if="row.endTime">{{ formatDateNew(row.endTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="excludeTime" label="刨除时间" align="center" />
        <el-table-column prop="minutePrice" label="分钟价格" align="center" />
        <el-table-column prop="receivablePrice" label="应收价格" align="center" />
        <el-table-column prop="netReceiptsPrice" label="实收价格" align="center" />

        <el-table-column prop="payStatus" label="支付状态" align="center">
          <template #default="{row}">
            <el-tag :type="row.payStatus === 1 ? 'success' : 'danger'">
              {{ row.payStatusName }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="payTransactors" label="收款办理人" align="center" />
        <el-table-column prop="remake" label="备注" align="center" show-overflow-tooltip />

        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template #default="{row}">
            <el-button
                size="small"
                type="primary"
                link
                @click="handleEditRecord(row)"
            >
              修改
            </el-button>
            <el-button
                size="small"
                type="danger"
                link
                @click="handleDeleteRecord(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :total="total"
          :page-sizes="[10, 20, 30]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          class="mt15"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <RecordDialog
        ref="recordDialogRef"
        @refresh="fetchTableData"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, FolderAdd } from '@element-plus/icons-vue';
import { getJdList, delRecord, getJlist } from '/@/api/jd/index';
import { formatDateNew } from '/@/utils/formatTime';
import RecordDialog from './addRowRole.vue';

// 组件引用
const recordDialogRef = ref();

// 数据状态
// const loading = ref(false);
const tableData = ref([]);
const total = ref(0);
const wellList = ref([]);

// 搜索参数
const searchParams = reactive({
  dataTime: [],
  jid: '',
  payStatus: '',
  keyword: ''
});

// 分页参数
const pagination = reactive({
  pageNum: 1,
  pageSize: 10
});

// 获取井列表
const fetchWellList = async () => {
  try {
    const res = await getJlist({ pageNum: 1, pageSize: 9999 });
    wellList.value = res.data.rows;
  } catch (error) {
    console.error('获取井列表失败:', error);
  }
};

// 获取表格数据
const fetchTableData = async () => {
  try {
    // loading.value = true;

    const params = {
      ...searchParams,
      ...pagination,
      startTime: searchParams.dataTime?.[0] || '',
      endTime: searchParams.dataTime?.[1] || ''
    };

    const { data } = await getJdList(params);
    tableData.value = data.rows;
    total.value = data.total;
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败');
  } finally {
    // loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.pageNum = 1;
  fetchTableData();
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  fetchTableData();
};

// 页码改变
const handlePageChange = (page: number) => {
  pagination.pageNum = page;
  fetchTableData();
};

// 新增记录
const handleAddRecord = () => {
  recordDialogRef.value.openDialog('add');
};

// 编辑记录
const handleEditRecord = (row) => {
  recordDialogRef.value.openDialog('edit', row);
};

// 删除记录
const handleDeleteRecord = async (row) => {
  try {
    await ElMessageBox.confirm('此操作将永久删除该记录，是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await delRecord({ id: row.id });
    ElMessage.success('删除成功');
    fetchTableData();
  } catch (error) {
    console.error('删除失败:', error);
  }
};

// 初始化
onMounted(() => {
  fetchWellList();
  fetchTableData();
});
</script>

<style scoped lang="scss">
.system-dic-container {
  .el-table {
    --el-table-row-height: 40px;

    :deep(.el-table__cell) {
      padding: 8px 0;
    }
  }

  .text-right {
    text-align: right;
  }

  .mt10 {
    margin-top: 10px;
  }
}
</style>
